package com.tl.commonlibrary.ui.adapter;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * Created by a on 2015/4/27.
 */
public class ViewHolder {
    private SparseArray<View> views;
    private Context context;
    private int position;
    private View convertView;

    public ViewHolder(Context context, int layoutId, int position,ViewGroup parent) {
        this.context = context;
        views = new SparseArray<View>();
        this.position = position;
        convertView = LayoutInflater.from(context).inflate(layoutId, parent,false);
        convertView.setTag(this);
    }

    public static ViewHolder get(Context context, int layoutId, int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            return new ViewHolder(context, layoutId, position,parent);
        } else {
            return (ViewHolder) convertView.getTag();
        }
    }

    /**
     * 获取指定的控件
     *
     * @param viewId 控件id
     * @param <T>    控件类名
     * @return
     */
    public <T extends View> T getView(int viewId) {
        if (viewId > 0) {
            T t = (T) views.get(viewId);
            if (t == null) {
                t = (T) convertView.findViewById(viewId);
                views.append(viewId, t);
            }
            return t;
        }
        throw new IllegalArgumentException("wrong viewId");
    }

    public ViewHolder setText(int viewId, CharSequence text) {
        TextView view = (TextView) views.get(viewId);
        if (view != null) {
            view.setText(text);
        }
        return this;
    }

    public ViewHolder setText(int viewId, int resid) {
        TextView view = (TextView) views.get(viewId);
        if (view != null) {
            view.setText(resid);
        }
        return this;
    }

    public ViewHolder setImageView(int viewId, int resid) {
        ImageView view = (ImageView) views.get(viewId);
        if (view != null) {
            view.setImageResource(resid);
        }
        return this;
    }

    public ViewHolder setImageView(int viewId, Drawable drawable) {
        ImageView view = (ImageView) views.get(viewId);
        if (view != null) {
            view.setImageDrawable(drawable);
        }
        return this;
    }

    public ViewHolder setBackgroundResource(int viewId, int resid) {
        View view = views.get(viewId);
        if (view != null) {
            view.setBackgroundResource(resid);
        }
        return this;
    }

    public ViewHolder setBackgroundColor(int viewId, int color) {
        View view = views.get(viewId);
        if (view != null) {
            view.setBackgroundColor(color);
        }
        return this;
    }
    public View getConvertView() {
        return convertView;
    }
}
